package LocalCRM::DBI;

use base 'LocalCRM';
use DBI;

sub new
{
    my $class= shift;
    my $self = $class->SUPER::new();

    my $dsn = sprintf 'dbi:mysql:database=%3$s;host=%1$s;port=%2$d',
		$self->{_cfg}->val('DB','Host')||'localhost',
		$self->{_cfg}->val('DB','Port')||'3306',
		$self->{_cfg}->val('DB','Name');

    $self->{_db} = DBI->connect($dsn,$self->{_cfg}->val('DB','User'),$self->{_cfg}->val('DB','Pass')) || die('Unable to connect DB');
    $self->{_db}->do('SET NAMES utf8');

    return $self;
}

sub getById
{
    my $self = shift;
    my $tbl= $_[0];
    my $id = $_[1];

    if ( $id )
    {
	my $sth = $self->{_db}->prepare(sprintf 'SELECT * FROM `%s`.`%s` WHERE `id`=? LIMIT 1',$self->{_cfg}->val('DB','Name'),$tbl);

	if ( $sth->execute($id) )
	{
	    my $row = $sth->fetchrow_hashref();

	    foreach my $key ( keys %{$row} )
	    {
		$row->{$key} =~ s/\\\"/\"/g;
	    }

	    return $row;
	}
    }
}

1;
